import React, { useState } from 'react'
import type { ComplianceItem } from '@/types/work'
import { 
  ComplianceType, 
  ProgressStatus,
  getRiskLevelText,
  getComplianceStatusText 
} from '@/types/work'
import ComplianceForm from './ComplianceForm'
import DeleteConfirmModal from '@/components/common/DeleteConfirmModal'
import { showMessage } from '@/components/common/MessageTip'
import { useBusiness } from '@/stores/useBusinessStore'

interface ComplianceCardProps {
  item: ComplianceItem
  updateItem: (item: ComplianceItem) => void
  deleteItem: (id: string) => void
}

const ComplianceCard: React.FC<ComplianceCardProps> = ({ 
  item, 
  updateItem, 
  deleteItem
}) => {
  const [isExpanded, setIsExpanded] = useState(false)
  const [isEditFormOpen, setIsEditFormOpen] = useState(false)
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
  
  // 获取业务系统信息，判断是否为数据安全评估
  const { selectedBusiness } = useBusiness()
  const isDataSecurityAssessment = selectedBusiness?.assessmentType === '105'

  // 根据成熟度等级获取颜色（不同透明度）
  const getMaturityColor = (level: number) => {
    const baseColor = '#9A334F'
    const opacity = 0.3 + (level * 0.14) // level 1: 0.44, level 2: 0.58, level 3: 0.72, level 4: 0.86, level 5: 1.0
    const hex = Math.round(opacity * 255).toString(16).padStart(2, '0')
    return `${baseColor}${hex}`
  }

  // 处理删除按钮点击
  const handleDeleteClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation()
    if (item.source_type === 'system') {
      showMessage('warning', '系统内置检查项不允许删除')
      return
    }
    setIsDeleteModalOpen(true)
  }
  
  // 获取进度状态的文本
  const getProgressStatusText = (status: ProgressStatus) => {
    switch (status) {
      case ProgressStatus.COMPLETED:
        return '已完成'
      case ProgressStatus.REMEDIATION:
        return '整改中'
      case ProgressStatus.IN_PROGRESS:
        return '进行中'
      default:
        return '未知状态'
    }
  }
  

  return (
    <div className="bg-card rounded-lg shadow-sm border border-border overflow-hidden transition-all duration-300 flex">
      {/* 左侧色块指示器 */}
      <div className={`w-2 ${item.compliance_type === ComplianceType.RISK ? 'bg-destructive' : 'bg-green-600'}`}></div>
      
      <div className="flex-1">
        {/* 卡片头部 - 状态标签栏 */}
        <div className="flex items-center px-3 py-1 border-b border-border">
          {/* 状态标签 */}
          <div className="flex flex-wrap gap-2">
            <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${item.compliance_type === ComplianceType.RISK ? 'bg-destructive/10 text-destructive' : 'bg-green-100 text-green-700'}`}>
              {item.compliance_type === ComplianceType.RISK ? '风险项' : '保障项'}
            </span>
            
            {/* 风险等级标签（仅风险项） */}
            {item.compliance_type === ComplianceType.RISK && item.risk_level && (
              <span className="text-xs font-medium px-2 py-0.5 rounded-full bg-accent text-accent-foreground">
                风险等级: {getRiskLevelText(item.risk_level, selectedBusiness?.assessmentType)}
              </span>
            )}
            
            {/* 进度状态标签 */}
            <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${item.progress_status === ProgressStatus.COMPLETED ? 'bg-green-100 text-green-700' : item.progress_status === ProgressStatus.REMEDIATION ? 'bg-destructive/10 text-destructive' : 'bg-secondary text-secondary-foreground'}`}>
              {getProgressStatusText(item.progress_status)}
            </span>
            
            {/* 合规状态标签（仅保障项） */}
            {item.compliance_type === ComplianceType.GUARANTEE && (
              <span className="text-xs font-medium px-2 py-0.5 rounded-full bg-accent text-accent-foreground">
                {getComplianceStatusText(item.compliance_status, selectedBusiness?.assessmentType)}
              </span>
            )}
            
            {/* 成熟度等级标签（仅数据安全评估） */}
            {isDataSecurityAssessment && item.maturity_level && (
              <span 
                className="text-xs font-medium px-2 py-0.5 rounded-full text-white"
                style={{ backgroundColor: getMaturityColor(item.maturity_level) }}
              >
                成熟度等级{item.maturity_level}
              </span>
            )}
          </div>
        </div>
      
        {/* 卡片内容 */}
        <div 
          className="p-4 cursor-pointer"
          onClick={() => setIsExpanded(!isExpanded)}
        >
          <div className="flex-1">
            <h3 className="text-lg font-medium text-foreground mb-2">{item.title}</h3>
            <p className="text-sm text-muted-foreground line-clamp-2">
              {item.description}
            </p>
            
            {/* 最后更新时间 */}
            <div className="flex justify-end mt-2">
              <p className="text-xs text-muted-foreground/70">最后更新: {item.updated_at ? new Date(item.updated_at).toLocaleDateString('zh-CN') : '2023-05-23'}</p>
            </div>
          </div>
        </div>
      
        {/* 展开的详细内容 */}
        {isExpanded && (
          <div className="p-4 pt-0 border-t border-border">
            {/* 详细信息部分 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div>
                <h4 className="text-sm font-medium text-foreground mb-1">检查指引</h4>
                <p className="text-sm text-muted-foreground">{item.guide}</p>
              </div>
              <div>
                <h4 className="text-sm font-medium text-foreground mb-1">检查描述</h4>
                <p className="text-sm text-muted-foreground">{item.inspector}</p>
              </div>
            </div>
            
            {/* 附件列表 */}
            <div className="mb-4">
              <h4 className="text-sm font-medium text-foreground mb-2">证明材料</h4>
              {item.attachments.length > 0 ? (
                <div className="flex flex-wrap gap-2">
                  {item.attachments.map(attachment => (
                    <a 
                      key={attachment.id}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-xs px-2 py-1 bg-secondary text-secondary-foreground rounded-full flex items-center"
                    >
                      {attachment.name}
                      <span className="text-xs text-muted-foreground ml-1">
                        ({Math.round(attachment.size / 1024)} KB)
                      </span>
                    </a>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground">无证明材料</p>
              )}
            </div>
            
            {/* 操作按钮 */}
            <div className="flex justify-end space-x-2 mt-4">
              <button
                onClick={handleDeleteClick}
                className="px-3 py-1.5 bg-destructive text-destructive-foreground rounded-md hover:bg-destructive/90 transition-colors text-sm"
              >
                删除
              </button>
              <button
                onClick={() => setIsEditFormOpen(true)}
                className="px-3 py-1.5 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 transition-colors text-sm"
              >
                编辑
              </button>
            </div>
          </div>
        )}
        
        {/* 编辑表单模态框 */}
        {isEditFormOpen && (
          <ComplianceForm
            mode="edit"
            initialData={item}
            onClose={() => setIsEditFormOpen(false)}
            onSubmit={(updatedItem, callback) => {
              updateItem(updatedItem as ComplianceItem)
              setIsEditFormOpen(false)
              if (callback) {
                callback(updatedItem as ComplianceItem)
              }
            }}
          />
        )}

        {/* 删除确认弹窗 */}
        <DeleteConfirmModal
          isOpen={isDeleteModalOpen}
          onClose={() => setIsDeleteModalOpen(false)}
          onConfirm={() => {
            deleteItem(item.id)
            setIsDeleteModalOpen(false)
          }}
          itemName={item.title}
          title="确认删除检查项"
          message="确定要删除这个检查项吗？"
          dangerMessage="删除后，该检查项及其所有相关数据将被永久删除。"
        />
      </div>
    </div>
  )
}

export default ComplianceCard
